package com.adminx.service;

import java.util.ArrayList;  
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.core.GrantedAuthority;  
import org.springframework.security.core.authority.GrantedAuthorityImpl;  
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.adminx.dao.AccountDao;
import com.adminx.entity.Account;
import com.adminx.entity.MyUserDetails;

@Service
@Transactional(propagation=Propagation.REQUIRED)
public class MyUserDetailsService implements UserDetailsService{

	protected static Logger LOGGER = Logger.getLogger(MyUserDetailsService.class);
	
	@Autowired
	private AccountDao accountDao;
	
	/**
	 * 访问角色权限 
	 */
	@Override
	public MyUserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {
		
		MyUserDetails securityUser = null;
		
		try {
			// 搜索数据库以匹配用户登录名
			Account account = this.accountDao.findByUserName(username);
			
			if(account == null){
				LOGGER.info("没有找到用户！");
			}
			
			List<Object> codeList = this.accountDao.findAuthorityCodeByAccountID(account.getAccountId());
			Collection <GrantedAuthority> auths = new ArrayList<GrantedAuthority>();
			for (Object obj : codeList) {
				auths.add(new  GrantedAuthorityImpl(obj.toString()));
			}
			securityUser = new MyUserDetails(account.getUserName(), account.getPassWord().toLowerCase(), true, true, true, true,auths);
			securityUser.setAccount(account);

		} catch (Exception e) {
			LOGGER.error("账号或密码错误！");
			throw new UsernameNotFoundException("账号或密码错误！");
		}
		return securityUser;
	}

	/**
	 * 加载权限资源映射
	 * @return
	 */
	public Map<String, Collection<ConfigAttribute>> loadResourcesAndAuthority(){
		Map<String, Collection<ConfigAttribute>> resourceMap = new HashMap<String, Collection<ConfigAttribute>>();
		try{
			List<Object[]> authorityResourceRelations = this.accountDao.findAuthorityResourceRelation();
			for(Object[] obj:authorityResourceRelations){
				Collection<ConfigAttribute> co = new ArrayList<ConfigAttribute>();
				co.add(new SecurityConfig(obj[0].toString()));
				resourceMap.put(obj[1].toString(), co);
			}
		}catch(Exception e){
			System.err.println("【安全框架】加载权限资源映射错误！");
		}	
		return resourceMap;
	}
}
